from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response 
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from forms import *
from models import *
from game import *


@login_required
def index(request):
    if len(Character.objects.all()) == 0:
        return HttpResponseRedirect("/character/")
    else:
        ## colocar autenticacao de usuario e senho aqui com character
        return HttpResponseRedirect("/game/1")

def newCharacter(request):
    message = None
    limit = Config.objects.get(id=1).max_skills
    if 'skillset' in request.session.keys():
        skillset = request.session['skillset']
    else:
        skillset = []
    if request.method == 'POST':
        if 'skillstotrain' in request.POST.keys():
            if len(skillset) < limit:
                skill = Skill.objects.get(id=request.POST['skillstotrain'])
                if skill not in skillset:
                    skillset.append(skill)
            else:
                message = 'there is a maximum of ' + str(limit) + ' skill per character'
        if 'removeskill' in request.POST.keys():
            skillset.remove(Skill.objects.get(id=request.POST['removeskill']))
        if 'name' in request.POST.keys():
            if not request.POST['name'] == 'None':
                if not request.POST['location'] == 'None':
                    c = Character()
                    c.name = Name.objects.get(id=request.POST['name'])
                    c.save()
                    for skill in skillset:
                        c.train(skill)
                    return goToLocation(request, c.id, request.POST['location'])
                else:
                    message = 'you need to choose a location to save a character.'
            else:
                message = 'you need to choose a name to save a character.'
    skilltrain = SkillTrainForm()
    characterform = CharacterForm()
    
    request.session['skillset'] = skillset
    
    return render_to_response('skillchallenge/newcharacter.html',
                              {'skillform' : skilltrain, 
                               'characterform' : characterform,
                               'skillset' : skillset,
                               'message' : message,
                               'can_save' : len(skillset) == limit,
                               'skill_limit' : limit},
                              context_instance=RequestContext(request))

def goToLocation(request, p_id, id):
    the_game = __get_game__(request, p_id)
    the_game.player_fire(
                         the_game.location_engine.move(Location.objects.get(id=id), True),
                         Character.objects.get(id=p_id))
    return HttpResponseRedirect('/game/' + str(p_id))

def game(request, p_id):
    the_game = __get_game__(request, p_id)
    messages = the_game.messages()
    available = the_game.player_available()
    options = the_game.affordable(available)
    current_tick = Tick.objects.latest()
    options = [Option.objects.create(event=option, tick=current_tick) for option in options]
    
    expensive = the_game.expensive(available)
    inventory = the_game.item_engine.inventory_list()
    quest = the_game.quest_set()
    completed = None
    if the_game.completed_quests():
        completed = ', '.join([questa.name for questa in the_game.completed_quests()])
    failed = None
    if the_game.failed_quests():
        failed = ', '.join([questa.name for questa in the_game.failed_quests()])
    return render_to_response('skillchallenge/game.html',
                              {'event_messages' : messages, 
                               'options' : options,
                               'expensive' : expensive,
                               'inventory' : inventory,
                               'quest' : quest, 
                               'char_id' : p_id,
                               'score' : the_game.score(),
                               'completed' : completed,
                               'failed' : failed,
                               'action_points' : the_game.action_points()},
                              context_instance=RequestContext(request))

def option(request, p_id, id):
    the_game = __get_game__(request, p_id)
    try:
        opt = Option.objects.get(id=id)
        if (opt.tick.tick != Tick.objects.latest().tick):
            return HttpResponseRedirect('/error/1')
        if (opt.event in the_game.player_available()):
            the_game.player_fire(opt.event, Character.objects.get(id=p_id))
    except:
        pass
    return HttpResponseRedirect('/game/' + str(p_id))

def tick(request, p_id):
    the_game = __get_game__(request, p_id)
    the_game.tick()
    return HttpResponseRedirect('/game/' + str(p_id))

def error(request, type):
    error = None
    if type == 1:
        error = 'At least one Tick has passed until last time you had that option, please, refresh the game and try again.'
    return render_to_response('skillchallenge/error.html',
                              {'error' : error,},
                              context_instance=RequestContext(request))

def __get_game__(request, char_id):
    if not 'game' in request.session.keys():
        request.session['game'] = Game(Character.objects.get(id=char_id))
    request.session['game'].update_tick()
    return request.session['game']